local require = require
local uu      = require("modules.commhm.utils")
local http    = require("modules.business_common.utils.business_http")
local config  = require("modules.business_common.business_config")

-- desc    : 云服接口
-- swagger : http://124.70.174.136:8002/swagger/index.html
local _M = {
    _VERSION = "0.0.0.1",
}

local ngx = ngx
local setmetatable = setmetatable

function _M:new(invoker, key)
    local mt = { __index = _M }
    return setmetatable({
        invoker = invoker,
        key = key
    }, mt)
end


function _M:http_post(router, data, header)
    local uri = config.get_cloud_server_url() .. router
    local body = uu.table2json(data)
    local request = {
        invoker  = self.invoker,
        key      = self.key,
        signType = 'md5',
        md5      = ngx.md5(body),
        ts       = ngx.time(),
    }
    request.sign = ngx.md5( uu.getStringBySortKey2( request ))
    header = header or {
        ["Content-Type"] = "application/json",
        ["Connection"]   = "Keep-Alive",
        ["User-Agent"]   = "mnw",
    }

    local result = uu.json2table(http.Post(uri, request, body, header) or '')
    if uu.tableIsEmpty(result) or result.code ~= 0 then
        return false
    end

    return true, result.data
end

-- !@ namespace : 该游戏某个数据集名称，e.g. ds_2_100000:global
-- !@ id        : 地图ID, e.g. 800000
-- !@ key       : 普通数据存储Key, e.g. testInt1
-- !@ value     : 设置key对应的值, e.g. 100501
function _M:SetDHSValue(id, namespace, key, value)
    return self:http_post('/api/v1/dhs/setValue', {
        namespace = namespace,
        aid       = id,
        key       = key,
        value     = value,
    }) and true or false
end

-- !@ namespace : 该游戏某个数据集名称，e.g. ds_2_100000:global
-- !@ id        : 地图ID, e.g. 800000
-- !@ key       : 普通数据存储Key, e.g. testInt1
function _M:GetDHSValue(id, namespace, key)
    local succ, result = self:http_post('/api/v1/dhs/getValue', {
        namespace = namespace,
        aid       = id,
        key       = key,
    })
    if not succ then
        return false
    end

    return true, result.value
end

return _M